"""Radio Simulator Agent Server"""

from flask import Flask, render_template, request, jsonify, Response
import json
import time
import os
import sys

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from agents.interface import AgentInterface


app = Flask(__name__, template_folder='.')
agent = AgentInterface()


@app.route('/')
def index():
    """Serve the chat interface"""
    return render_template('chat.html')


@app.route('/chat', methods=['POST'])
def chat():
    """Handle chat messages"""
    user_message = request.json.get('message', '')
    
    def generate():
        # 使用AgentInterface处理用户消息
        for char in agent.chat_with_user(user_message):
            # 模拟打字效果
            time.sleep(0.01)
            yield char
    
    return Response(generate(), mimetype='text/plain')


@app.route('/run_simulation', methods=['POST'])
def run_simulation():
    """Run the radio simulation with provided file path"""
    file_path = request.json.get('file_path', '')
    
    if not file_path:
        return jsonify({'error': '未提供文件路径'}), 400
    
    # 这里应该调用实际的模拟函数
    # 暂时返回模拟结果
    result = {
        'status': 'success',
        'message': f'已开始处理文件: {file_path}',
        'details': '模拟运行中...'
    }
    
    return jsonify(result)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)